package com.drools.controller;

import com.drools.entity.Order;
import com.drools.entity.OrderRange;
import com.drools.utils.RuleEngine;
import com.drools.utils.RuleEngineImpl;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by LANCHUNQIAN on 2016/11/21.
 */
@RestController
@RequestMapping("/setDirector")
public class SetDirector {
    private static final Logger RUN_LOG = LoggerFactory.getLogger(DRLController.class);

    private RuleEngine ruleEngine = new RuleEngineImpl();

    @RequestMapping("/rule")
    @ResponseBody
    public String setRule(String orderRangeJson){

        System.out.println("json from ajax:" + orderRangeJson);

        JSONArray array = JSONArray.fromObject(orderRangeJson);
        List<OrderRange> orderRanges = JSONArray.toList(array, new OrderRange(), new JsonConfig());//参数1为要转换的JSONArray数据，参数2为要转换的目标数据，即List盛装的数据

        System.out.println(orderRanges);

        System.out.println("Count of OrderRange : " + orderRanges.size());
        for(int i = 0;i < orderRanges.size();i ++){
            OrderRange orderRange = orderRanges.get(i);
            System.out.println(orderRange);
            String rule = "\n import com.drools.entity.Order\n" +
                          "   import java.math.BigDecimal\n" +
                            "\nrule \"Set Director" + orderRange.getLowerLimit() +"\"\n" +
                            "\twhen \n" +
                            "\t\t$order : Order (price.compareTo(BigDecimal.valueOf(" + orderRange.getLowerLimit() + ")) > 0  && " +
                            " price.compareTo(BigDecimal.valueOf(" + orderRange.getUpperLimit() + ")) <= 0);\n" +
                            "\tthen\n" +
                            "\t\t$order.setDirector(\"" + orderRange.getDirector().toString() + "\");\n" +
                            "\tend\n";

            ruleEngine.addRule(rule);
        }
        return "ok";
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test(String orderPrice){
        System.out.println(orderPrice);
        Order order = new Order();
        order.setPrice(BigDecimal.valueOf(Double.parseDouble(orderPrice)));
        ruleEngine.initEngine();
        ruleEngine.executeRuleEngine(order);
        RUN_LOG.info("The director of the order is :{}",order.getDirector());
        return order.getDirector();
    }
}
